iT邦幫忙

2022 iThome 鐵人賽

DAY 12
0
Modern Web

clojure 刷刷鍋系列 第 12

Clojure 肉片 -第 12 塊

  • 分享至 

  • xImage
  •  

【心得】

  1. 看別人的答案才意識到,根本不需要 count 1 / -1 個數有幾個,值本身就是數量本身,所以直接 sum 起來比較大小就好!
  2. 用自己的寫法時,為區分 men / women 時也嘗試用了第一次 group-by(map count (vals (group-by #(= 1 %) [1 -1 -1]))) => (1 2) 但似乎寫不出比較直覺看得懂的方式,後面還要再處理才能比較 list 內的兩個值,所以採用 count filter 的做法

【今日湯底】

Task
King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.

To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year's party. He gave you a list of integers of all the party goers.

Arthur needs you to return true if he needs to invite more women or false if he is all set.

Input/Output
[input] integer array L ($a in PHP)
An array (guaranteed non-associative in PHP) representing the genders of the attendees, where -1 represents women and 1 represents men.

2 <= L.length <= 50

[output] a boolean value

true if Arthur need to invite more women, false otherwise.

(必須通過以下測試)

(ns kata.test
  (:require [clojure.test :refer :all]
            [kata :refer :all]))
(defn tester [l e]
  (testing (str "Testing for " l)
    (is (= (invite-more-women l) e))))
(deftest basic-tests
  (tester [1 -1 1] true)
  (tester [-1 -1 -1] false)
  (tester [1 -1] false)
  (tester [1 1 1] true))

【我的答案】

(ns kata)
(defn invite-more-women [L]
  (let [men-count (count (filter #(= 1 %) L))
        women-count (count (filter #(= -1 %) L))]
    (> men-count women-count))
)

思路:

  1. 想用 filter 將 men / women 分類
  2. 只要 men count > women count 就算是符合題目要求的判斷 妹子不夠(?)

【其他人的答案】

(ns kata)
(defn invite-more-women [L]
  (> (reduce + L) 0))

上一篇
Clojure 肉片 -第 11 塊
下一篇
Clojure 肉片 -第 13 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言